import Vue from 'vue';
import VueRouter from 'vue-router';

import Layouts from '../layouts/index.vue';
import pageLayout from '../layouts/components/pageLayout';

import systemList from './modules/systemList';

import store from '@/store'

Vue.use(VueRouter);

export const routes = [
  {
    path: '/',
    name: 'Home',
    component: Layouts,
    meta: { title: '首页', icon: 'el-icon-s-home', keepAlive: true },
    redirect: '/home',
    children: [
      {
        path: '/home',
        meta: { title: '首页', icon: 'el-icon-s-home', keepAlive: true },
        component: () => import('../views/home/index.vue')
      },
      {
        path: '/home/sys',
        meta: { title: '系统', icon: 'el-icon-s-home', keepAlive: true },
        component: pageLayout,
        children: [
          {
            path: '/home/sys/user',
            meta: { title: '用户管理1', icon: 'el-icon-user', keepAlive: true },
            component: () => import('../views/system/user/index.vue')
          },
          {
            path: '/home/sys/person1',
            meta: { title: '个人中心', icon: 'el-icon-user-solid', keepAlive: true },
          }
        ]
      }
    ]
  },
  systemList,
  {
    path: '/about',
    name: 'About',
    meta: { title: '关于', icon: 'el-icon-info', keepAlive: true },
    component: () => import('../views/About.vue')
  },
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登录', icon: 'el-icon-info', keepAlive: true },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Regiter',
    meta: { title: '注册', icon: 'el-icon-info', keepAlive: true },
    component: () => import('../views/Regiter.vue')
  }
]

export const permissionRoutes = []

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export function resetRouter() {
  const newRouter = new VueRouter({
    scrollBehavior: () => ({ y: 0 }),
    routes: routes
  })
  router.matcher = newRouter.matcher
}

// 解决重复点击导航时，控制台出现报错 
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

// 前置路由拦截器
router.beforeEach((to, from, next) => {
  // 设置当前页签名称
  document.title = to.meta.title;
  next();
});

router.afterEach((to) => {
  if (to.name && to.meta.needCache) {
    store.commit('tagsView/ADD_CACHE_VIEW', to.name)
  }

  if (to.meta === undefined || to.meta.notNeedAuth) {
    return
  }

  if (to.meta.fixed) {
    store.dispatch('tagsView/addFixedVisitedView', {
      name: to.name,
      fullPath: to.fullPath,
      meta: to.meta,
    })
  } else {
    store.commit('tagsView/ADD_VISITED_VIEW', {
      name: to.name,
      fullPath: to.fullPath,
      meta: to.meta,
    })
  }
});

export default router
